<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2016/8/14
 * Time: 17:07
 */

namespace Aoe\Intent\Request\Http;

use function array_forget;
use function array_get;
use function array_has;
use function array_set;

/**
 * # Session 管理类
 */
class Session
{
    private bool $open = false;
    
    /**
     * ## 设置session值
     *  * 当Key为数组时为批量设置
     *
     * @param array|string $key   key值
     * @param mixed        $value value值
     *
     * @return bool
     */
    public function set(array | string $key, mixed $value = ''): bool
    {
        $this->start();
        
        if (!is_array($key)) {
            array_set($_SESSION, $key, $value);
        } else {
            foreach ($key as $k => $v) Session::set($k, $v);
        }
        
        return true;
    }
    
    /**
     * session_start()
     *
     * @return void
     */
    private function start(): void
    {
        if (!$this->open) $this->open = session_start();
    }
    
    /**
     * ## 获取session值
     *
     * @param string     $key
     * @param mixed|null $default
     *
     * @return mixed
     */
    public function get(string $key, mixed $default = null): mixed
    {
        $this->start();
        
        return array_get($_SESSION, $key, $default);
    }
    
    /**
     * ## 删除session值
     *
     * @param string $key
     */
    public function del(string $key): void
    {
        $this->start();
        
        array_forget($_SESSION, $key);
    }
    
    /**
     * ## 查询
     *
     * @param string $key
     *
     * @return bool
     */
    public function has(string $key): bool
    {
        return $this->open && array_has($_SESSION, $key);
    }
    
    /**
     * ## 清空session
     *
     * @noinspection PhpUnused
     */
    public function clear(): void
    {
        if (!$this->open) return;
        
        $_SESSION = [];
    }

    public function getId(): string
    {
        return session_id();
    }
}